package server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import serverGUI.GUI;

import lejos.pc.comm.NXTComm;
import lejos.pc.comm.NXTCommFactory;
import lejos.pc.comm.NXTInfo;

import net.*;

public class ServiceManager implements NetServiceDelegate, NetConnectionDelegate {

	NetConnection iPhoneConnection;
	NetConnection nxtConnection;
	public GUI gui;

	public ServiceManager() {
		try
		{
			System.out.println("ServiceManager :: Creating connections...");
			
			iPhoneCommands.loadIni();
					
			NXTComm nxtComm = NXTCommFactory.createNXTComm(NXTCommFactory.BLUETOOTH);
			NXTInfo nxtInfo = new NXTInfo(NXTCommFactory.BLUETOOTH, "NXT", "00:16:53:0a:54:1c");
			nxtComm.open(nxtInfo);
			DataOutputStream outStream = new DataOutputStream(nxtComm.getOutputStream());
			DataInputStream inStream = new DataInputStream(nxtComm.getInputStream());
			NetConnection conn = new NetConnection(inStream, outStream);
			nxtConnection = conn;
			nxtConnection.delegate = this;
			
			NetLogger.flags = NetLogger.NetLogAll - NetLogger.NetLogMessage;
			NetService service = new NetService("_rc._tcp");
			service.register();
			service.delegate = this;
			service.start();
			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {}
	}
	
	public void connectionMadeToNetService(NetService netService, NetConnection connection) {
		connection.delegate = this;
		connection.setPingEnabled(true);
		iPhoneConnection = connection;
	}

	public void connectionReceivedMessage(NetConnection connection, NetMessage message) {
		NetCommand command = NetCommand.valueOf(message);
		
		if(iPhoneConnection == null || nxtConnection == null) return;
		
		if(connection == iPhoneConnection)
		{
			int executedCommand = (new iPhoneCommands(command, nxtConnection)).execute();
			if (executedCommand != 0) {
				System.out.println("Error! Unknown iPhone Command: " + command.getHead());
			}
		}
		if(connection == nxtConnection)
		{
			NXTCommands nxtCommands= new NXTCommands(command, iPhoneConnection);
			nxtCommands.serviceManager = this;
			int executedCommand = nxtCommands.execute();
			if (executedCommand != 0) {
				System.out.println("Error! Unknown NXT Command: " + command.getHead());
			}
		}
	}

	public void connectionReceivedPingBack(NetConnection connection, long ping) {

	}
	
	public void shutdown() throws IOException {
		System.out.println("ServiceManager :: Closing sonnections...");
		if (iPhoneConnection != null)
			iPhoneConnection.close();
		if (nxtConnection != null)
			nxtConnection.close();		
	}
}